package com.maincode.fragment.nearby;


import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.example.risen.androidwcc.R;
import com.lidroid.xutils.BitmapUtils;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.client.HttpRequest;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.lidroid.xutils.view.annotation.event.OnClick;
import com.lidroid.xutils.view.annotation.event.OnItemClick;
import com.maincode.activity.ActionActivity;
import com.maincode.model.CommentBean;
import com.util.HttpUrl;
import com.util.SystemParams;
import com.util.Tools;
import com.util.xutil.HttpParams;
import com.util.xutil.HttpRequestCallBack;
import com.util.xutil.HttpUtils;
import com.view.RoundAngleImageView;
import com.view.XListView;

import java.util.List;

/**
 * A simple {@link Fragment} subclass.
 */
public class DynamicCommentFragment extends Fragment implements XListView.IXListViewListener {
    ActionActivity activity;
    View v;
    String DynamicId = "";
    int pagerNum = 0;
    public String replayToCommentId = "";
    public String replayToUid = "";
    public int commentState = -1;  //-1表示点的空白区域 0表示回复 1表示评论

    @ViewInject(R.id.xList)
    XListView xList;
    @ViewInject(R.id.etCommentContent)
    public EditText etCommentContent;
    List<CommentBean.Comment> data;

    public DynamicCommentFragment() {

    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        activity = (ActionActivity) getActivity();
        activity.headBar.setBarText("评论");
        activity.headBar.setVisibility(View.VISIBLE);
        activity.headBar.setBarRightSH(View.INVISIBLE);
        v = inflater.inflate(R.layout.fragment_dynamic_comment, container, false);
        ViewUtils.inject(this, v);
        xList.setXListViewListener(this);
        xList.setPullLoadEnable(true);
        xList.setPullRefreshEnable(false);
        xList.mFooterView.setVisibility(View.GONE);
        getData();
        etCommentContent.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (commentState != 0) {
                    commentState = 1;
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
        return v;
    }

    private void getData() {
        DynamicId = getArguments().getString("DynamicId");
        HttpParams httpParams = new HttpParams(HttpUrl.getUrl(HttpUrl.COMMENTS));
        httpParams.putString("id", DynamicId);
        httpParams.putString("start", (pagerNum * 15) + "");
        httpParams.putString("limit", "15");
        HttpUtils httpUtils = HttpUtils.getInstance();
        httpUtils.send(HttpRequest.HttpMethod.POST, httpParams.toString(), new HttpRequestCallBack<CommentBean>(CommentBean.class, getActivity()) {

            @Override
            protected void onSuccess(CommentBean commentBeen) {
                etCommentContent.setText("");
                data = commentBeen.data;
                xList.setAdapter(new CommentAdapter());
                xList.stopLoadMore();
                xList.mFooterView.setVisibility(View.GONE);
            }

            @Override
            public void onFailure(HttpException arg0, String arg1) {
                super.onFailure(arg0, arg1);
                activity.showToast("加载失败");
                xList.stopLoadMore();
                xList.mFooterView.setVisibility(View.GONE);
            }
        });
    }

    private void comment() {
        String content = etCommentContent.getText().toString().trim();
        if (content.length() == 0) {
            activity.showToast("请输入评论内容");
            return;
        }
        HttpParams httpParams = new HttpParams(HttpUrl.getUrl(HttpUrl.COMMENT));
        httpParams.putString("contentUnicode", content);
        httpParams.putString("momentsId", DynamicId);
        if (!replayToCommentId.equals("")) {
            httpParams.putString("replayToCommentId", replayToCommentId);
        }
        if (!replayToUid.equals("")) {
            httpParams.putString("replayToUid", replayToUid);
        }

        HttpUtils httpUtils = HttpUtils.getInstance();
        httpUtils.send(HttpRequest.HttpMethod.POST, httpParams.toString(), new HttpRequestCallBack<String>(String.class, activity, "正在提交评论") {
            @Override
            protected void onSuccess(String s) {
                if (s.contains("content")) {
                    getData();
                } else {
                    JSONObject jsonObject = JSON.parseObject(s);
                    activity.showToast(SystemParams.getInstance().getErrorMsg(jsonObject.getString("data")));
                }
            }

            @Override
            public void onFailure(HttpException arg0, String arg1) {
                super.onFailure(arg0, arg1);
                activity.showToast("评论失败");
            }
        });
    }

    @Override
    public void onRefresh() {
        pagerNum++;
        getData();
    }

    @Override
    public void onLoadMore() {
        xList.mFooterView.setVisibility(View.VISIBLE);
        pagerNum = 0;
        getData();
    }

    @OnItemClick(R.id.xList)
    private void lvOnItemClick(AdapterView<?> parent, View view, int position, long id) {
        commentState = 0;
        replayToCommentId = data.get(position - 1).id + "";
        replayToUid = data.get(position - 1).owner.id + "";
        etCommentContent.setHint("回复 " + data.get(position - 1).owner.nickname + " :");
        InputMethodManager inputManager = (InputMethodManager) etCommentContent.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
        inputManager.showSoftInput(etCommentContent, 0);
    }

    @OnClick(R.id.btnComment)
    private void commentClick(View v) {
        comment();
    }

    class CommentAdapter extends BaseAdapter {

        @Override
        public int getCount() {
            if (data == null)
                return 0;
            return data.size();
        }

        @Override
        public Object getItem(int position) {
            return null;
        }

        @Override
        public long getItemId(int position) {
            return 0;
        }

        class ViewHodler {
            RoundAngleImageView ivHead;
            TextView tvUserName;
            TextView tvContent;
            TextView tvDate;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ViewHodler viewHodler = new ViewHodler();
            if (convertView == null) {
                convertView = getActivity().getLayoutInflater().inflate(R.layout.layout_comment_item, null);
                viewHodler.ivHead = (RoundAngleImageView) convertView.findViewById(R.id.ivHead);
                viewHodler.tvUserName = (TextView) convertView.findViewById(R.id.tvUserName);
                viewHodler.tvContent = (TextView) convertView.findViewById(R.id.tvContent);
                viewHodler.tvDate = (TextView) convertView.findViewById(R.id.tvDate);
                convertView.setTag(viewHodler);
            } else {
                viewHodler = (ViewHodler) convertView.getTag();
            }
            BitmapUtils bu = new BitmapUtils(getActivity());
            bu.display(viewHodler.ivHead, HttpUrl.PICURL + "/" + data.get(position).owner.defaultHeadsmall);
            viewHodler.tvUserName.setText(data.get(position).owner.nicknameUnicode);
            String commentContent = "";
            if (data.get(position).replayToUser != null) {
                commentContent = "回复" + data.get(position).replayToUser.nicknameUnicode + "：";
            }
            viewHodler.tvContent.setText(commentContent + data.get(position).contentUnicode);
            viewHodler.tvDate.setText(Tools.formatTime(data.get(position).gmtCreated + ""));
            return convertView;
        }
    }
}
